package org.example;

import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

@Data
//封装请求数据
public class MyHttpRequest {
    private InputStream inputStream;
    //请求的uri
    private String uri;
    //请求方法
    private String method;
    private Socket socket;

    public MyHttpRequest(InputStream inputStream,Socket socket) {

        this.inputStream = inputStream;
        this.socket=socket;
    }
    //解析请求输入流
    public void parse(){
        StringBuffer request=new StringBuffer(2048);
        //创建字节数组
        byte[] buffer=new byte[2048];
        int pos;//实际的字节数
        try {
            pos=inputStream.read(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //遍历字节数组拼接到StringBuffer
        for(int i=0;i<pos;i++){
            request.append((char)buffer[i]);
        }
        System.out.println(request.toString());
        parseUriAndMethod(request.toString());
    }
    //解析请求输入流中的uri和method
    public void parseUriAndMethod(String requestString){
        //前两个空格的位置
        int index1,index2;
        index1=requestString.indexOf(' ');
        if(index1!=-1){
            method=requestString.substring(0,index1);
            index2=requestString.indexOf(' ',index1+1);
            if(index2>index1){
                //截取子串
                uri=requestString.substring(index1+1,index2);
            }
        }
    }

}
